package com.huo.qq.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.DefaultHttpClient;

import com.huo.http.HttpService;
import com.huo.common.StringUtil;

/**
 * <p>Description: </p>
 * @author Huoyan
 * @version 1.0
 * <p>Copyright 2011</p>
 */

public class VerifyCode extends HttpService{
	
	public VerifyCode(){}
	
	public VerifyCode(DefaultHttpClient client){
		setClient(client);
	}
	
	public String getVerifyCode(String qq, JLabel lbl){
		//登录步骤1,获取登陆表单信息，检查当前QQ是否需要验证码登录
		String checkIdUrl = GlobalURL.CHECK_ID_URL + qq;
		//发送请求
		String res = getReturnStr(checkIdUrl);
		
		//使用正则匹配获取验证码编号
		// ptui_checkVC('0','!ZLE');返回这个就不需要获取验证码了。验证码就是!ZLE
		// ptui_checkVC('1','95ab7db15e5ab17f50f25d33598259e83ccc098c4af2f8a4');这个长字符串就需要使用了
		String checkType = StringUtil.findPattern("\\,\\'([!\\w]+)\\'", res);
		
		String check = ""; //客户端输入的验证码
		//判断是否需要验证码登录
		if (!checkType.startsWith("!")) {
			//需要输入验证码登录
			byte[] ibs = readCheckImage(GlobalURL.CHECK_IMAGE_URL + "&uin=" + qq + "&vc_type=" + checkType);
			//将图片设置在组件JLable上
			ImageIcon ii = new ImageIcon(ibs);
			lbl.setIcon(ii);
		}else{
			//无需验证码登录
			check = checkType;
		}
		return check;
	}
	
	/**
	 * 获取验证码图片字节
	 * @param uri
	 */
	private byte[] readCheckImage(String uri){
		HttpResponse res = get(uri);
		byte[] b = null;
		try {
			InputStream in = res.getEntity().getContent();
			b = IOUtils.toByteArray(in);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}
	
	/**
	 * 将验证码保存成文件
	 * @param url
	 * @param fileUrl
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public void saveVerificationcCode(String url,String fileUrl) throws ClientProtocolException, IOException{
		HttpResponse res = get(url);
		InputStream in= res.getEntity().getContent();
		int temp = 0;
		File file = new File(fileUrl);
		FileOutputStream out = new FileOutputStream(file);
		while((temp=in.read())!=-1){
		 out.write(temp);
		}
		in.close();
		out.close();
	}
}
